package com.vogue.supplymall.match.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
import com.vogue.supplymall.account.domain.model.User;
import com.vogue.supplymall.account.domain.service.BaseCodeService;
import com.vogue.supplymall.account.domain.service.BaseRegistinfoService;
import com.vogue.supplymall.account.domain.service.UserService;
import com.vogue.supplymall.common.domain.tool.MessageSourceUtils;
import com.vogue.supplymall.match.domain.dto.BaseDTO;
import com.vogue.supplymall.match.domain.dto.BuyerOrganDTO;
import com.vogue.supplymall.match.domain.dto.EnterpriseDTO;
import com.vogue.supplymall.match.domain.dto.SellerOrganDTO;
import com.vogue.supplymall.match.domain.dto.UserDTO;
import com.vogue.supplymall.match.domain.service.ColValidateService;
import com.vogue.supplymall.match.domain.service.MatchOrganService;

import ch.qos.logback.core.joran.util.beans.BeanUtil;

@RestController
public class MatchUserOrganController extends BaseController{
	@Autowired
	private MatchOrganService matchOrganService;
	@Autowired
    private MessageSourceUtils msu;
	@Autowired
	private ColValidateService colValidateService;
    @Resource
    private BaseCodeService baseCodeService;
    @Resource
    private UserService userService;
    @Resource
    private BaseRegistinfoService baseRegistinfoService;
	
	/**
	 * 企业信息
	 * @param request
	 * @param response
	 * @param baseDTO
	 */
	@RequestMapping(value="/ns/v1/match/enterprise",method=RequestMethod.POST)
	public String matchEnterprise(HttpServletRequest request,HttpServletResponse response,
			@RequestBody(required = true) BaseDTO<EnterpriseDTO> baseDTO) {
		
		boolean resultFlag=true;
		String message=msu.getMessage("global.system.success",null);
		Map<String, Object> resultMap=new HashMap<>();
		List<Map<String, Object>> errList=new ArrayList<>();

		//首先对数据进行验证
		try {
			errList = colValidateService.enterpriseValidate(baseDTO);
		} catch (Exception e) {
			resultFlag=false;
			message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
		}
		
		if(errList.size()>0) {
			resultFlag=false;
			message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
		}else {
			try {
				//保存企业信息
				matchOrganService.matchEnterprise(baseDTO);
			} catch (Exception e1) {
				resultFlag=false;
				message=msu.getMessage("match.validate.uperr.ent", new String[]{});
			}
			
		}
		
		//返回数据
		resultMap.put("result", resultFlag);
		resultMap.put("message", message);
		resultMap.put("details", errList);
		String json=new Gson().toJson(resultMap);
		
		return json;
	}
	/**
	 * 买家机构信息
	 * @param request
	 * @param response
	 * @param baseDTO
	 */
	@RequestMapping(value="/ns/v1/match/buyerOrgan",method=RequestMethod.POST)
	public String matchBuyerOrgan(HttpServletRequest request,HttpServletResponse response,
			@RequestBody(required = true) BaseDTO<BuyerOrganDTO> baseDTO) {
		
		boolean resultFlag=true;
		String message=msu.getMessage("global.system.success", null);
		Map<String, Object> resultMap=new HashMap<>();
		List<Map<String, Object>> errList=new ArrayList<>();
		
		//首先对数据进行校验
		try {
 			errList = colValidateService.buyerOrganValidate(baseDTO);
		} catch (Exception e2) {
			resultFlag=false;
			message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
		}

		if(errList.size()>0) {
			resultFlag=false;
			message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
			
		}else {
			try {
				//保存买家机构信息
				matchOrganService.matchBuyerOrgan(baseDTO);
			} catch (Exception e1) {
				resultFlag=false;
				message=msu.getMessage("match.validate.uperr.org", null);
			}
		}
		
		//返回数据
		resultMap.put("result", resultFlag);
		resultMap.put("message", message);
		resultMap.put("details", errList);
		String json=new Gson().toJson(resultMap);
		
		return json;
	}
	
	/**
	 * 用户信息
	 * @param request
	 * @param response
	 * @param baseDTO
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/ns/v1/match/user",method=RequestMethod.POST)
	public String matchUser(HttpServletRequest request,HttpServletResponse response,
			@RequestBody(required = true) BaseDTO<List<UserDTO>> baseDTO) {
		
		boolean resultFlag=true;
		String message=msu.getMessage("global.system.success", null);
		Map<String, Object> resultMap=new HashMap<>();
		List<Map<String, Object>> errList=new ArrayList<>();
		
		//首先对数据进行校验
		try {
			errList = colValidateService.buyerValidate(baseDTO);
		} catch (Exception e2) {
			resultFlag=false;
			message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
		}
		
		if(errList.size()>0) {
			resultFlag=false;
			message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
			
		}else {
			
			try {
				//判断上传的用户是新增还是更新，给oper列赋值，同时判断上传的用户电话是否符合要求，不符合要求返回errList
				Map<String, Object> cuMap=this.checkUserInfo(baseDTO, errList);
				errList=(List<Map<String, Object>>) cuMap.get("errList");	
				
				if(errList.size()>0) {
					resultFlag=false;
					message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
				}else {
					baseDTO=(BaseDTO<List<UserDTO>>) cuMap.get("baseDTO");
					 if (baseDTO != null && baseDTO.getData() != null) {
						 
						//保存用户信息
						matchOrganService.matchUser(baseDTO);	
					 }else {
						 resultFlag=false;
						 message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
					 }
				}
				
			} catch (Exception e1) {
				resultFlag=false;
				message=msu.getMessage("match.validate.uperr.buyyer", null);
			}
		}
		
		//返回数据
		resultMap.put("result", resultFlag);
		resultMap.put("message", message);
		resultMap.put("details", errList);
		String json=new Gson().toJson(resultMap);
		
		return json;
	}
	/**
	 * 卖家机构信息
	 * @param request
	 * @param response
	 * @param baseDTO
	 */
	@RequestMapping(value="/ns/v1/match/sellerOrgan",method=RequestMethod.POST)
	public String matchSellerOrgan(HttpServletRequest request,HttpServletResponse response,
			@RequestBody(required = true) BaseDTO<List<SellerOrganDTO>> baseDTO) {
		
		boolean resultFlag=true;
		String message=msu.getMessage("global.system.success", null);
		Map<String, Object> resultMap=new HashMap<>();
		List<Map<String, Object>> errList=new ArrayList<>();
		
		//首先对数据进行校验
		try {
			errList = colValidateService.sellerOrganValidate(baseDTO);
		} catch (Exception e2) {
			resultFlag=false;
			message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
		}
			
		if(errList.size()>0) {
			resultFlag=false;
			message=msu.getMessage("match.validate.uperr.datastructure", new String[]{});
			
		}else {
			try {
				matchOrganService.matchSellerOrgan(baseDTO);
			} catch (Exception e1) {
				resultFlag=false;
				message=msu.getMessage("match.validate.uperr.seller", null);
			}
		}
		
		//返回数据
		resultMap.put("result", resultFlag);
		resultMap.put("message", message);
		resultMap.put("details", errList);
		String json=new Gson().toJson(resultMap);
		
		return json;
	}
	
	/**
	 * 检查用户电话是否正确，并给oper赋值
	 */
	public Map<String, Object> checkUserInfo(BaseDTO<List<UserDTO>> baseDTO,List<Map<String, Object>> errList) throws Exception{
		BaseDTO<List<UserDTO>> newBaseDTO=new BaseDTO<>();
		List<UserDTO> uDTOList=new ArrayList<>();
		Map<String, Object> returnMap=new HashMap<>();
		List<String> midList=new ArrayList<>();
		String userTel="";
		String addTel="";
		
		//得到数据源
		List<UserDTO> userDTOs=baseDTO.getData();
		
		//根据sysCodeId找到所有已上传的人员信息
		Long sysCodeId = baseCodeService.checkSysCodeValidity(baseDTO.getRegistercode());
		List<User> userList=userService.findUserBySys(sysCodeId);
		
		if(userList.size()>0) {
			for(User user:userList) {
				if(StringUtils.isNotBlank(user.getMatchid())) {
					midList.add(user.getMatchid());
				}
			}
		}
		
		//循环传过来的额员工，判断是新增还是更新
		for(UserDTO userDTO:userDTOs) {
			if(!midList.contains(userDTO.getMatchid())) {			//新增
				
				//置oper标志
				UserDTO ud=new UserDTO();
				BeanUtils.copyProperties(ud, userDTO);
				ud.setOper(0);
				uDTOList.add(ud);
				
				userTel+=userDTO.getTel()+",";
				addTel+="'"+userDTO.getTel()+"',";
			}else{													//更新
				
				//置oper标志
				UserDTO ud=new UserDTO();
				BeanUtils.copyProperties(ud, userDTO);
				ud.setOper(1);
				uDTOList.add(ud);
				
				//判断手机号是否唯一
				this.updateTelIsUnion(errList, userDTO, sysCodeId);
				
			}
		}
		
		newBaseDTO.setEnterpriseid(baseDTO.getEnterpriseid());
		newBaseDTO.setRegistercode(baseDTO.getRegistercode());
		newBaseDTO.setRegistertel(baseDTO.getRegistertel());
		newBaseDTO.setData(uDTOList);
		
		//手机号判断
		String[] telArry=userTel.split(",");
		List<String> telList=Arrays.asList(telArry);
		
		//用户手机号不能与注册手机号冲突
		this.telConflictCheck(userTel, sysCodeId, errList,telList);
		
		//新上传的手机号中不能有重复的手机号
		this.telRepeatCheck(errList, telList);
		
		//用户手机号要唯一
		this.addTelUnion(errList, addTel);
		
		//装配结果
		returnMap.put("errList", errList);
		returnMap.put("baseDTO", newBaseDTO);
		
		return returnMap;
	}

	/**
	 * 更新用户时判断更新的手机号是否唯一
	 */
	public void updateTelIsUnion(List<Map<String, Object>> errList,UserDTO userDTO,Long sysCodeId) {
		List<User> list=userService.findUserByTel(userDTO.getTel());
		if(list.size()>0) {
			for(User user:list) {
				Long defSysCodeId=user.getDefsyscodeid();
				String userMatchId=user.getMatchid();
				String newUserMatchId =userDTO.getMatchid();
				
				if((!newUserMatchId.equals(userMatchId))||(!defSysCodeId.equals(sysCodeId))) {
					List<String> infoList=new ArrayList<>();
					infoList.add(msu.getMessage("match.validate.telIsExist", new String[] {user.getTel()}));
					Map<String, Object> errMap=colValidateService.setValueForErrMap(msu.getMessage("global.system.tel", null),"",infoList,"3100");
					errList.add(errMap);
					break;
				}
			}
		}

	}

	/**
	 * 用户手机号不能与注册手机号冲突
	 */
	public void telConflictCheck(String userTel,Long sysCodeId,List<Map<String, Object>> errList,List<String> telList) {
		String newTel=baseRegistinfoService.findTelBySysCodeId(sysCodeId);
		for(String tel:telList) {
			if(newTel.equals(tel)) {
				List<String> infoList=new ArrayList<>();
				infoList.add(msu.getMessage("match.validate.telIsSysTel", new String[] {tel}));
				Map<String, Object> errMap=colValidateService.setValueForErrMap(msu.getMessage("global.system.tel", null),"",infoList,"3100");
				errList.add(errMap);
			}
		}
	}
	
	/**
	 * 新上传的手机号不能有重复
	 */
	@SuppressWarnings("rawtypes")
	public void telRepeatCheck(List<Map<String, Object>> errList,List<String> telList) {
		HashSet hs=new HashSet<>(telList);
		if(hs.size()<telList.size()) {
			List<String> infoList=new ArrayList<>();
			infoList.add(msu.getMessage("match.validate.telIsRepeat",null));
			Map<String, Object> errMap=colValidateService.setValueForErrMap(msu.getMessage("global.system.tel", null),"",infoList,"3100");
			errList.add(errMap);
		}
	}
	
	/**
	 * 用户手机号要唯一
	 */
	public void addTelUnion(List<Map<String, Object>> errList,String addTel) {
		if(StringUtils.isNotBlank(addTel)) {
			addTel=addTel.substring(0,addTel.length()-1);
			List<User> list=userService.findUserByTel(addTel);
			if(list.size()>0&&list.get(0)!=null) {
				for(User user:list) {
					String userMatchId=user.getMatchid();
					if(StringUtils.isNoneBlank(userMatchId)) {
						List<String> infoList=new ArrayList<>();
						infoList.add(msu.getMessage("match.validate.telIsExist", new String[] {user.getTel()}));
						Map<String, Object> errMap=colValidateService.setValueForErrMap(msu.getMessage("global.system.tel", null),"",infoList,"3100");
						errList.add(errMap);
					}
				}			
			}
		}
	}
	
}
